﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TableProto;
using UnityEngine.UI;
using WCBG.ToolsForUnity.Tools;
using WCBG.ToolsForUnity.Extension;

public class StudyEnglishBasePart : InitiativeBasePart, IEasyAudio, IEasyEffect
{
    public StudyEnglishBasePart(uint infoID)
    {
        _DataID = infoID;
        if (TableProtoLoader.EnglishLetterInfoDict.ContainsKey(_DataID))
        {
            info = TableProtoLoader.EnglishLetterInfoDict[_DataID];
        }
        else
        {
            Debug.LogError("get englishLetterInfo error! dataID:" + _DataID);
        }
    }

    private Transform _Scene;
    public Transform Scene
    {
        get { return _Scene; }
    }

    protected int m_partIndex;  //从0开始

    // 数据表对应数据ID
    private uint _DataID;
    public uint DataID
    {
        get { return _DataID; }
    }

    protected EnglishLetterInfo info = null;

    protected EnglishBaseMono gameAsset1 = null;
    protected EnglishBaseMono gameAsset2 = null;
    protected EnglishBaseMono gameAsset3 = null;

    protected Transform gameAsset1_Start;
    protected Transform gameAsset2_Start;
    protected Transform gameAsset3_Start;
    protected Transform gameAsset1_End;
    protected Transform gameAsset2_End;
    protected Transform gameAsset3_End;
    protected Transform gameAsset1_Out;
    protected Transform gameAsset2_Out;
    protected Transform gameAsset3_Out;


    protected readonly float gameDelayTime = 1f;   //游戏延迟开始

    protected readonly float sea_paopaoStartTime = 1.5f;   //海底泡泡初始化时间
    protected readonly float paddyfield_caoduoStartTime = 1.2f;   //麦田草垛初始化时间
    protected readonly float gameassetStartTime = 0.5f;   //元素初始化时间
    protected readonly float selectWaitTime = 0.5f;   //选中之后等待时间
    protected readonly float gameasset1OutTime = 1.5f;   //正确元素消失时间
    protected readonly float otherassetWaitTime = 2f;   //其它元素消失等待时间
    protected readonly float otherassetOutTime = 0.5f;   //其它元素消失时间
    protected readonly float paddyfield_caoduoOutTime = 1.2f;   //麦田草垛消失时间

    protected bool bLockInput = false;

    private Texture2D _LetterTexture;
    protected Texture2D LetterTexture
    {
        get
        {
            if (_LetterTexture == null)
            {
                string spriteName = info.bigorsmall == 1 ? info.name + "(big)" : info.name.ToLower() + "(small)";
                Sprite sprite = Res.LoadSprite(StudyPath.english_bigandsmall_letter_basepath + spriteName);

                if (sprite != null)
                {
                    _LetterTexture = FTools.CreateSquareTexture(sprite.ConvertToTexture2D());
                }
            }
            return _LetterTexture;
        }
    }

    protected override void OnPartStart()
    {
        base.OnPartStart();
        bLockInput = true;
        
        AddTimer(gameDelayTime, () => {
            OnGameStartDelay();
        });
    }

    protected override void OnPartStart(params object[] paramArray)
    {
        base.OnPartStart(paramArray);
        bLockInput = true;
        
        AddTimer(gameDelayTime, () =>
        {
            OnGameStartDelay();
        });
    }

    protected override void OnPartExit()
    {
        info = null;

        EventBus.Instance.BroadCastEvent(EventID.ON_ENGLISH_GAME_PART_EXIT);
    }

    protected override void AddEvent()
    {
        EventBus.Instance.AddEventHandler(EventID.ON_MOUSE_BUTTON_DOWN, OnMouseDown);
        EventBus.Instance.AddEventHandler(EventID.ON_MOUSE_BUTTON_HOVER, OnMouseHover);
        EventBus.Instance.AddEventHandler(EventID.ON_MOUSE_BUTTON_UP, OnMouseUp);
    }

    protected override void RemoveEvent()
    {
        EventBus.Instance.RemoveEventHandler(EventID.ON_MOUSE_BUTTON_DOWN, OnMouseDown);
        EventBus.Instance.RemoveEventHandler(EventID.ON_MOUSE_BUTTON_HOVER, OnMouseHover);
        EventBus.Instance.RemoveEventHandler(EventID.ON_MOUSE_BUTTON_UP, OnMouseUp);
    }

    protected virtual void OnGameStartDelay() { }

    protected virtual void OnMouseDown()
    {
        //Transform target = FTools.GetRaycastHitTargetByMousePoint((int)EGameLayerMask.ShadowProjecter);
        //if (target != null)
        //{
        //    StudyFixedActor fixedActor = target.GetComponent<StudyFixedActor>();
        //    if (fixedActor != null) fixedActor.PlayAnimation();
        //}

        //if (bLockInput) return;

        //Transform target = FTools.GetRaycastHitTargetByMousePoint();
        //if (target != null)
        //{
        //    EnglishBaseMono mono = target.GetComponent<EnglishBaseMono>();
        //    if (mono == null)
        //        return;
        //    if (mono.Letter == info.param_1)
        //    {
        //        Debug.Log("选择正确！");
        //        bLockInput = true;
        //        AddTimer(selectWaitTime, () =>
        //        {
        //            gameAsset1.StartYourShowtime(gameasset1OutTime);
        //            AddTimer(otherassetWaitTime, () =>
        //            {
        //                gameAsset2.LeaveTheStage(otherassetOutTime);
        //                gameAsset3.LeaveTheStage(otherassetOutTime);
        //                AddTimer(otherassetOutTime, () =>
        //                {
        //                    MedalWindow.Instance.ShowXunzhang(m_partIndex + 1, true, MedalWindow.EXZCountEnum.Four, () =>
        //                    {
        //                        OnPartComplete();
        //                    });
        //                });
        //            });
        //        });
        //    }
        //    else
        //    {
        //        mono.Shake(0.5f);
        //    }
        //    mono.PlayAudio();
        //}
    }

    protected virtual void OnMouseHover() { }
    protected virtual void OnMouseUp() { }

    protected virtual void SpawnGameAsset<T>(string assetPath) where T : EnglishBaseMono
    {
        Resource res = ResourceManager.Instance.GetResource(assetPath, typeof(GameObject), enResourceType.ScenePrefab);
        if (res.m_content != null)
        {
            gameAsset1 = Instantiate(res.m_content as GameObject, true).AddComponent<T>();
            gameAsset2 = Instantiate(res.m_content as GameObject, true).AddComponent<T>();
            gameAsset3 = Instantiate(res.m_content as GameObject, true).AddComponent<T>();
        }
        else
        {
            Debug.LogError("Load asset error! assetPath:" + assetPath);
        }
    }

    protected virtual void SpawnGameAsset<T>(string assetPath1, string assetPath2, string assetPath3) where T : EnglishBaseMono
    {
        List<string> rdList = new List<string>() { assetPath1 , assetPath2, assetPath3 };

        string _random1 = rdList[Random.Range(0, rdList.Count - 1)];
        rdList.Remove(_random1);
        gameAsset1 = Instantiate(_random1, true).AddComponent<T>();

        string _random2 = rdList[Random.Range(0, rdList.Count - 1)];
        rdList.Remove(_random2);
        gameAsset2 = Instantiate(_random2, true).AddComponent<T>();

        gameAsset3 = Instantiate(rdList[0], true).AddComponent<T>();
        rdList.Clear();
    }

    protected virtual void SetScene(Transform scene)
    {
        _Scene = scene;
    }

    protected virtual Transform CreateScene(string scenePath)
    {
        _Scene = Instantiate(scenePath, true).transform;

        Camera targetCamera = _Scene.Find("Camera").GetComponent<Camera>();
        //Camera targetCamera = scene.GetComponentInChildren<Camera>();
        if (targetCamera != null)
        {
            Camera.main.CopyFrom(targetCamera);
            targetCamera.gameObject.SetActive(false);
        }
        return _Scene;
    }



    protected void FindGameAssetPoints(Transform parent)
    {
        if (parent == null)
            return;
        gameAsset1_Start = parent.Find("GameAsset1_Start");
        gameAsset2_Start = parent.Find("GameAsset2_Start");
        gameAsset3_Start = parent.Find("GameAsset3_Start");
        gameAsset1_End = parent.Find("GameAsset1_End");
        gameAsset2_End = parent.Find("GameAsset2_End");
        gameAsset3_End = parent.Find("GameAsset3_End");
        gameAsset1_Out = parent.Find("GameAsset1_Out");
        gameAsset2_Out = parent.Find("GameAsset2_Out");
        gameAsset3_Out = parent.Find("GameAsset3_Out");
        if (gameAsset1_Start == null) Debug.LogError("gameAsset1_Start is null!");
        if (gameAsset2_Start == null) Debug.LogError("gameAsset2_Start is null!");
        if (gameAsset3_Start == null) Debug.LogError("gameAsset3_Start is null!");
        if (gameAsset1_End == null) Debug.LogError("gameAsset1_End is null!");
        if (gameAsset2_End == null) Debug.LogError("gameAsset2_End is null!");
        if (gameAsset3_End == null) Debug.LogError("gameAsset3_End is null!");

        if (gameAsset1_End != null) gameAsset1_End.gameObject.SetActive(false);
        if (gameAsset2_End != null) gameAsset2_End.gameObject.SetActive(false);
        if (gameAsset3_End != null) gameAsset3_End.gameObject.SetActive(false);
    }

    // 获取场景预先摆好的位置信息
    protected virtual void GetGameAssetPoints(int index, out Vector3 startPoint, out Vector3 endPoint, out Vector3 outPoint)
    {
        startPoint = Vector3.zero;
        endPoint = Vector3.zero;
        outPoint = Vector3.zero;
        switch (index)
        {
            case 1:
                startPoint = gameAsset1_Start == null ? Vector3.zero : gameAsset1_Start.position;
                endPoint = gameAsset1_End == null ? Vector3.zero : gameAsset1_End.position;
                outPoint = gameAsset1_Out == null ? Vector3.zero : gameAsset1_Out.position;
                break;
            case 2:
                startPoint = gameAsset2_Start == null ? Vector3.zero : gameAsset2_Start.position;
                endPoint = gameAsset2_End == null ? Vector3.zero : gameAsset2_End.position;
                outPoint = gameAsset2_Out == null ? Vector3.zero : gameAsset2_Out.position;
                break;
            case 3:
                startPoint = gameAsset3_Start == null ? Vector3.zero : gameAsset3_Start.position;
                endPoint = gameAsset3_End == null ? Vector3.zero : gameAsset3_End.position;
                outPoint = gameAsset3_Out == null ? Vector3.zero : gameAsset3_Out.position;
                break;
        }
    }

    protected virtual void SetGameAssetRandomPoint()
    {
        Vector3 startPoint = Vector3.zero;
        Vector3 endPoint = Vector3.zero;
        Vector3 outPoint = Vector3.zero;

        List<int> rdList = new List<int>();
        rdList.Add(1);
        rdList.Add(2);
        rdList.Add(3);

        int _random1 = rdList[Random.Range(0, rdList.Count - 1)];
        rdList.Remove(_random1);
        GetGameAssetPoints(_random1, out startPoint, out endPoint, out outPoint);
        gameAsset1.Init(startPoint, endPoint, outPoint, info.param_1, info.param_1_offset, info.audio_param_1, info.param_1_atlas, info.param_1_texture, gameassetStartTime);

        int _random2 = rdList[Random.Range(0, rdList.Count - 1)];
        rdList.Remove(_random2);
        GetGameAssetPoints(_random2, out startPoint, out endPoint, out outPoint);
        gameAsset2.Init(startPoint, endPoint, outPoint, info.param_2, info.param_2_offset, info.audio_param_2, info.param_2_atlas, info.param_2_texture, gameassetStartTime);

        GetGameAssetPoints(rdList[0], out startPoint, out endPoint, out outPoint);
        gameAsset3.Init(startPoint, endPoint, outPoint, info.param_3, info.param_3_offset, info.audio_param_3, info.param_3_atlas, info.param_3_texture, gameassetStartTime);
        rdList.Clear();
    }

    protected virtual Transform SetHintLetter()
    {
        if (Scene != null)
        {
            Transform target = Scene.Find("HintLetter");
            if (target != null)
            {
                Text text = target.GetComponentInChildren<Text>();
                text.text = info.bigorsmall == 1 ? info.name : info.name.ToLower();
                //text.color = Color.red;
            }
            return target;
        }
        return null;
    }


    protected Vector3 GetScreenToWorldPoint(Camera camera, float x, float y, float depth = 20)
    {
        return camera.ScreenToWorldPoint(new Vector3(x, y, depth));
    }

    protected void PlayLetterEffect()
    {
        if (WindowManager.Instance.eventSystem.IsPointerOverGameObject())
            return;
        if (LetterTexture != null)
        {
            this.PlayEffectEx(StudyPath.effect_502003067, FTools.GetRaycastHitPointByMousePoint(), 5, LetterTexture);
        }
    }
    
    protected void PlayEffect(string path, Vector3 position, float destroyTime)
    {
        GameObject effect = Instantiate(path, true);
        if (effect != null)
        {
            effect.transform.position = position;
            GameObject.Destroy(effect, destroyTime);
        }
    }

    // index 从1开始 （ 1 - 3 ）
    protected float GetDelayTime(int index)
    {
        switch (index)
        {
            case 1:
                return 0.24f;
            case 2:
                return 0.12f;
            case 3:
                return 0f;
            default:
                return 0;
        }
    }


}
